package com.software.graduationproject.modules.marketers.service;


import cn.hutool.core.bean.BeanUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.metadata.Page;

import com.baomidou.mybatisplus.core.metadata.PageImpl;
import com.google.common.base.Strings;
import com.software.graduationproject.commons.config.OSSConfig;
import com.software.graduationproject.commons.enums.MerchantType;
import com.software.graduationproject.commons.select.Select;
import com.software.graduationproject.commons.util.DateUtils;
import com.software.graduationproject.modules.comment.mapper.CommentMapper;
import com.software.graduationproject.modules.comment.object.CommentVo;
import com.software.graduationproject.modules.food.object.FoodCommentVo;
import com.software.graduationproject.modules.marketers.entity.Marketers;
import com.software.graduationproject.modules.marketers.mapper.MarketersMapper;
import com.software.graduationproject.modules.marketers.object.MarketersCommentVo;
import com.software.graduationproject.modules.marketers.object.MarketersVo;
import com.software.graduationproject.modules.marketers.object.MarketersCreateQo;
import com.software.graduationproject.modules.marketers.object.MarketersUpdateQo;

import com.software.graduationproject.modules.user.entity.User;
import com.software.graduationproject.modules.user.mapper.UserMapper;
import com.software.graduationproject.modules.user.object.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MarketersService : 商家表
 * ---------------------------------------------------------------------------------------------------------------------
 */
@Service
@Slf4j
public class MarketersService {

    @Autowired
    private MarketersMapper marketersMapper;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    public void createQo(MarketersCreateQo marketersCreateQo) {
        String merchantImg = marketersCreateQo.getMerchantImg();
        // 解码Base64字符串为字节数组
        byte[] decodedBytes = Base64.getDecoder().decode(merchantImg);
        // 创建 MockMultipartFile 对象
        MultipartFile file = new MockMultipartFile("img.jpg", decodedBytes);
        String upload = this.upload(file);
        Marketers marketers = new Marketers();
        BeanUtil.copyProperties(marketersCreateQo, marketers);
        marketers.setMerchantImg(upload);
        marketersMapper.insert(marketers);
    }

    /**
     * 阿里云OSS文件上传
     *
     * @param file
     */
    public String upload(MultipartFile file) {

        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        //获取原生文件名
        String originalFilename = file.getName();
        //JDK8的日期格式
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //拼装OSS上存储的路径
        String folder = dft.format(time);
        long fileName = System.currentTimeMillis();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //在OSS上bucket下的文件名
        String uploadFileName = "img/" + folder + "/" + fileName + extension;
        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                return "https://"+bucketName+"."+endPoint+"/"+uploadFileName;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage());
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        return null;
    }

    public MarketersVo selectVo(Long id) {
        MarketersVo marketersVo = new MarketersVo();
        Marketers marketers = marketersMapper.selectById(id);
        BeanUtil.copyProperties(marketers,marketersVo);
        return marketersVo;
    }

    public Page<MarketersVo> selectPageVo(Select select){
        return marketersMapper.selectPageVo(select);
    }

    public List<MarketersVo> selectListVo(Select select){
        return marketersMapper.selectListVo(select);
    }

    public List<MarketersVo> searchAllBySelect(Select select) {
        List<Integer> types = MerchantType.searchValuesByKeyword(select.getParam("search"));
        select.addParam("types",types);
        return marketersMapper.searchAllBySelect(select);
    }

    public MarketersCommentVo selectMarketersComment(Long id) {
        MarketersCommentVo marketersCommentVo = marketersMapper.selectMarketersComment(id);
        String commentsId = marketersCommentVo.getCommentsId();
        if (Strings.isNullOrEmpty(commentsId)) {
            return marketersCommentVo;
        }
        Marketers marketers = new Marketers();
        marketers.setId(id);
        marketers.setRateValue(marketersCommentVo.getAverageRateValue());
        marketersMapper.updateById(marketers);
        String[] split1 = commentsId.split(",");
        List<Long> ids = Arrays.stream(split1)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<CommentVo> commentsByIds = commentMapper.findCommentsByIds(ids);
        // 根据评论的userId查询对应的用户信息，并存储在Map中
        List<UserVo> list = new ArrayList<>();
        for (CommentVo comment : commentsByIds) {
            Long userId = comment.getUserId();
            Long shoppingCartId = comment.getShoppingCartId();
            String foodName = marketersMapper.findFoodNameByCartId(shoppingCartId);
            UserVo userVo = new UserVo();
            User user = userMapper.selectById(userId);
            userVo.setId(user.getId());
            userVo.setNickname(user.getNickname());
            userVo.setPicUrl(user.getPicUrl());
            userVo.setFoodName(foodName);
            userVo.setTime(DateUtils.formatDateToDate(comment.getCreatedDate()));
            // 将评论添加到用户的评论列表中
            userVo.setCommentVo(comment);
            list.add(userVo);
        }
        marketersCommentVo.setUserVos(list);
        return marketersCommentVo;
    }
}
